package cn.edu.java.thread.原子类;

import lombok.SneakyThrows;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class AtomicIntegerFieldUpdaterDemo {

    // 定义一个包含int字段的类
    static class Counter {
        public volatile int count1;
        public volatile int count2;
    }


    @SneakyThrows
    public static void main(String[] args) {
        // 创建AtomicIntegerFieldUpdater实例，指定要更新的字段类型和字段名
        AtomicIntegerFieldUpdater<Counter> counterAtomicIntegerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Counter.class, "count1");

        // 创建Counter对象
        Counter counter = new Counter();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    counterAtomicIntegerFieldUpdater.getAndAdd(counter, 1);
                    counter.count2++;
                }
            }
        };

        new Thread(runnable).start();
        new Thread(runnable).start();

        Thread.sleep(100);

        System.out.println("升级后的结果："+ counter.count1);  // 升级后的结果：2000
        System.out.println("普通变量的结果："+ counter.count2);  // 普通变量的结果：1970

    }


}

